package tau.dimes.config.login;

import java.util.Map;
import java.util.TreeMap;

import tau.dimes.config.ConfigurationException;
import tau.dimes.config.ConfigurationNode;
import tau.dimes.config.ConfigurationSource;
import tau.dimes.util.ReflectionHelper;

public class LoginConfiguration
{
	private static LoginConfiguration instance;
	
	private static String SECTION_NAME = "loginConfiguration";
	private static String USERS_NODE_NAME = "users";
	private static String USER_NODE_NAME = "user";
	
	private final Map<String, User> users;
	
	private LoginConfiguration(ConfigurationSource source) throws ConfigurationException
	{
		users = new TreeMap<String, User>();
		
		ConfigurationNode loginNode = source.getConfigurationNode(SECTION_NAME);
		if (loginNode == null)
			throw new ConfigurationException(SECTION_NAME + " is missing from configuration.");

		try
		{
			ConfigurationNode usersNode = loginNode.getChild(USERS_NODE_NAME);
			if (usersNode != null)
				for (ConfigurationNode userNode : usersNode.getChildren(USER_NODE_NAME))
				{
					User user = new User();
					ReflectionHelper.SetProperties(user, userNode.getAttributes());
					users.put(user.getUsername(), user);
				}
		}
		catch (Exception e)
		{
			throw new ConfigurationException(e);
		}
	}
	
	public static LoginConfiguration getInstance()
	{
		return instance;
	}
	
	public static void initInstance(ConfigurationSource source) throws ConfigurationException
	{
		instance = new LoginConfiguration(source);
	}
	
	public static boolean validate(String username, String password)
	{
		if (getInstance().users.containsKey(username))
		{
			User user = getInstance().users.get(username);
			if (password.equals(user.getPassword()))
				return true;
		}
		
		return false;
	}
}
